<?php
/**
 * User: wanghousheng
 * Date: 2017/6/14
 * Time: 14:33
 * 微信登录
 */
class Wxoauth
{
    const GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    const GET_AUTH_CODE_URL = "https://open.weixin.qq.com/connect/qrconnect";
    const GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo";
    const GET_WAP_CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
    public $apiId;
    public $apiKey;
    public $callBackUrl;
    public $code;
    public function __construct($params=array()){
        if (empty($this->apiKey) || empty($this->apiId)){
            return $this->ApiState(false,'配置信息有误');
        }
        if (isset($params['APIId']) && $params['APIId']){
            $this->apiId = $params['APIId'];
        }else{
            $this->apiId = '';
        }
        if (isset($params['APIKEY']) && $params['APIKEY']){
            $this->apiKey = $params['APIKEY'];
        }else{
            $this->apiKey = '';
        }
        if (isset($params['BACKURL']) && $params['BACKURL']){
            $this->callBackUrl = $params['BACKURL'];
        }else{
            $this->callBackUrl = '';
        }
        $this->code = isset($_REQUEST['code'])? $_REQUEST['code'] : '';
    }
    /**
     * Name: pc 扫码登录
     * User: wanghousheng
     * Date: 2017/6/14
     * @param string $state(自定义值)
     * @param string $display(pc mobile)
     * @return string
     */
    public function login($state=''){
        if (empty($this->callBackUrl)){
            return $this->ApiState(false,'回调地址不能为空');
        }
        if (!$state) $state = md5(uniqid(rand(), TRUE));
        $params['appid'] = $this->apiId;
        $params['redirect_uri'] = $this->callBackUrl;
        $params['response_type'] = 'code';
        $params['scope'] = 'snsapi_login';
        $params['state'] =$state;
        $param =http_build_query($params,'','&');
        $login_url=self::GET_AUTH_CODE_URL."?".$param.'#wechat_redirect';
        $this->ApiState(true,'success',array('login_url'=>$login_url));
    }

    /**
     * Name: wap 微信登录
     * User: wanghousheng
     * Date: 2017/6/14
     * @param string $state
     * @return array
     */
    public function wapLogin($state=''){
        if (empty($this->callBackUrl)){
            return $this->ApiState(false,'回调地址不能为空');
        }
        if (!$state) $state = md5(uniqid(rand(), TRUE));
        $params['appid'] = $this->apiId;
        $params['redirect_uri'] = urlencode($this->callBackUrl);
        $params['response_type'] = 'code';
        $params['scope'] = 'snsapi_userinfo';
        $params['state'] = $state;
        $param =http_build_query($params,'','&');
        $login_url=self::GET_WAP_CODE_URL."?".$param.'#wechat_redirect';
        $this->ApiState(true,'success',array('login_url'=>$login_url));
    }

    /**
     * Name: 获取token
     * User: wanghousheng
     * Date: 2017/6/14
     * @return array
     */
    public function getToken(){
        $parms['appid'] = $this->apiId;
        $parms['secret'] = $this->apiKey;
        $parms['code'] = $this->code;
        $parms['grant_type'] = 'authorization_code';
        $param =http_build_query($parms,'','&');
        $url=self::GET_ACCESS_TOKEN_URL."?".$param;
        $res = json_decode($this->getUrl($url),true);
        if (isset($res['access_token']) && isset($res['openid'])){
            return array('access_token'=>$res['access_token'],'openid'=>$res['openid']);
        }else{
            return $this->ApiState(false,'token错误',$res);
        }
    }

    /**
     * Name: 获取用户信息
     * User: wanghousheng
     * Date: 2017/6/14
     * @param string $access_token
     * @param string $openid
     * @return array
     */
    public function getUserInfo($access_token='',$openid=''){
        if (empty($access_token) || empty($openid)){
            $res = $this->getToken();
            $access_token = $res['access_token'];
            $openid = $res['openid'];
        }
        $parms['access_token'] = $access_token;
        $parms['openid'] = $openid;
        $parms['lang'] = 'zh_CN';
        $param =http_build_query($parms,'','&');
        $url=self::GET_USER_INFO."?".$param;
        $result = json_decode($this->getUrl($url),true);
        if (isset($result['unionid']) && $result['unionid']){
            $result['openid'] = $result['unionid'];
            unset($result['unionid']);
        }
        return $this->ApiState(true,'success',$result);
    }
    private function getUrl($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        if (!empty($options)){
            curl_setopt_array($ch, $options);
        }
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    /**
     * Name: 返回状态
     * User: wanghousheng
     * Date: 2017/6/14
     * @param bool $status
     * @param string $msg
     * @param array $data
     * @return array
     */
    private function ApiState($status = true,$msg = 'success',$data = array()){
        return array('status'=>$status,'message'=>$msg,'data'=>$data);
    }
}